package sgi.server;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import sgi.message.*;
import ocsf.server.*;

public class SGIServer extends AbstractServer {
	  /**
	   * The default port to listen on.
	   */
	  final public static int DEFAULT_PORT = 5555;
	  private Connection connDB;
	  private SGIServerUI serverUI;
	  
	  public SGIServer(SGIServerUI serverUI)
	  {
		  super();
		  this.serverUI = serverUI;
		  serverUI.setVisible(true);
	  }
	 
	  public void initDBConnection(String dbName,String user, String pass) throws Exception
	  {
		  try 
			{
	            Class.forName("com.mysql.jdbc.Driver").newInstance();
	            connDB = DriverManager.getConnection("jdbc:mysql://localhost/"+dbName, user, pass);
	        } catch (Exception ex) {throw ex;}
	  }
	  
	  public void handleMessageFromClient
	    (Object msg, ConnectionToClient client)
	  {
			try 
			{
				Statement stmt = connDB.createStatement();
				switch(((Message)msg).getType())
				{
					case(Message.SELECT):
						serverUI.display("READ request.");
						ResultSet rs = stmt.executeQuery(((Message)msg).getQuery());
						while(rs.next())
							client.sendToClient(rs.getString(1));
						rs.close();
						break;
					case(Message.INSERT):
						serverUI.display("WRITE request.");
						stmt.executeUpdate(((Message)msg).getQuery());
						break;
					case(Message.DISPLAY):
						serverUI.display(((Message)msg).getQuery());
						break;
				}
				
			} catch (Exception e) {e.printStackTrace();}
	  }

}
